#from PIL import Image
from numpy import *
from scipy import optimize
import pyfits
from scipy import optimize

execfile(os.path.join(_path,"configslit.py"))

def gaussian(height, center_x, center_y, width_x, width_y):
     """Returns a gaussian function with the given parameters"""
     width_x = float(width_x)
     width_y = float(width_y)
     return lambda x,y: height*exp(
                 -(((center_x-x)/(width_x))**2+((center_y-y)/(width_y))**2)/2)

# First calculating an FWHM with the same size of the seeing.
# for this we use the relation between standard deviation and FWHM
# FWHM=2*sqrt(ln(2)*2)*desvpad

desvpad=seeing/(2.*numpy.sqrt(2.*numpy.log(2.)))

# Create the psf gaussian data as a function of the seeing

width_x=desvpad/pixsize
width_y=width_x*numpy.cos(razax)
Xin, Yin = mgrid[0:201, 0:201]
data = gaussian(1, 100, 100, width_x, width_y)(Xin, Yin)
data = data/data.sum()


# Convert array in an image, enbling us to rotate the image

#impil=Image.fromarray(data)
#impil=impil.rotate(PA,Image.BICUBIC)

#print PA
#pylab.imshow(impil)
#pylab.show()
#exit(0)

# Convert the data back to an array

datarot=numpy.asarray(data)
datarot=datarot[:,:]
datarot=asfarray(datarot)
datarot=flipud(datarot)    # Flipping the data (maybe NOT necessary)
    
# Find the coordinates of the center (in case it changed when
# the image was rotated)

ind=numpy.where(datarot == datarot.max())

# Cut the fraction of the image inside the slit

subdata=datarot[:, ind[1][0]-round(slitpix/2):ind[1][0]+round(slitpix/2)]
#print subdata.sum()
fracslit=subdata.sum()


#pyfits.writeto('frame11.fits',subdata,clobber=True)

# pix=numpy.array(out.getdata())
# pix.shape=(im.size[1],im.size[0])
# pyfits.writeto('girado.fits',pix)

# Generating a very ellongated ellipse
# and creating a fits file for it

# data = gaussian(1, 100, 100, 3.5, 2)(Xin, Yin)
# teste=Image.fromarray(data)
# im2=teste.rotate(25,Image.BICUBIC)
# srcarray=numpy.asarray(im2)
# a=srcarray[:,:]
# a=asfarray(a)
# a=flipud(a)
# pyfits.writeto('girado.fits',a)

# Substituing the gaussian data for a uniform data

# a=asfarray(srcarray)
# a=flipud(a)
# data=data/data.sum()
# a=a/a.sum()
# ind=numpy.where(a > 1E-34)
# a[ind]=1.
# pyfits.writeto('frame3.fits',a)
# a=a/a.sum()
# subdata=a[:, 90:110]
# subdata.sum()

# Re-finding the center after the rotation

# ind=numpy.where(data == data.max())


#image2array(out)

# The complete procedure is:

# data = gaussian(1, 100, 100, 3.5, 2)(Xin, Yin)
# teste=Image.fromarray(data)
# im2=teste.rotate(25,Image.BICUBIC)
# srcarray=numpy.asarray(im2)
# a=srcarray[:,:]
# a=asfarray(a)
# a=flipud(a)
# pyfits.writeto('frame3.fits',a)
# ind=numpy.where(a == a.max())
# ind
# a=a/a.sum()
# subdata=a[:, 91:111]
# pyfits.writeto('frame4.fits',subdata)
